package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {
//    阿里云访问链接
//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;
////    阿里云对象存储秘钥ID
//    @Value("${aliyun.oss.accessKeyId}")
//    private String accessKeyId;
////    阿里云对象存储secret
//    @Value("${aliyun.oss.accessKeySecret}")
//    private String accessKeySecret;
////    对象存储仓库名称
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName;
    @Autowired
    private AliOSSProperties aliOSSProperties;

    public String upload(MultipartFile file) throws IOException{
        String endpoint=aliOSSProperties.getEndpoint();
        String accessKeyId=aliOSSProperties.getAccessKeyId();
        String accessKeySecret=aliOSSProperties.getAccessKeySecret();
        String bucketName=aliOSSProperties.getBucketName();
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String newFileNme=UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName,newFileNme,inputStream);
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"//"+newFileNme;
        ossClient.shutdown();
        return url;
    }
}
